import 'dart:ui';
import 'package:get/get.dart';

class LocaleController {
  // 支持的语言列表 [语言代码, 国家代码, 显示名称]
  static final List<List<String>> langList = [
    ['zh', 'CN', '简体中文'],
    ['en', 'US', 'English'],
  ];

  static Locale defaultLanguage() => Locale(langList[0][0], langList[0][1]);

  static List<Locale> supportLocaleList() =>
      langList.map((e) => Locale(e[0], e[1])).toList();

  final language = CurrentLanguage(0, langList[0][2]).obs;

  List<String> get languageTextList => langList.map((e) => e[2]).toList();

  Future<void> initLanguage() async {
    changeLanguage(0);
  }

  Future<void> changeLanguage(int index) async {
    try {
      // 更新当前语言状态
      var lang = langList[index];
      language.value = CurrentLanguage(index, lang[2]);

      String langCode = lang[0];

      Get.updateLocale(Locale(langCode, lang[1]));
    } catch (e) {}
  }

  Future<void> setLanguage(String langCode) async {
    final index = langList.indexWhere((element) => element[0] == langCode);
    await changeLanguage(index);
  }
}

class CurrentLanguage {
  CurrentLanguage(this.index, this.text);

  final int index;
  final String text;
}
